# coding:utf-8 

import pprint
import sys
import time
import thread
import dircache
import math
import os
import operator
import string
from os import system
from agilityregister_auto import Ui_MainWindow
from agilityregister_vybrat_preteky_auto import Ui_vybrat_preteky_dialog
from agilityregister_udaje_dialog_auto import Ui_udajeDialog
from agilityregister_behy_dialog_auto import Ui_behyDialog
from agilityregister_startovka_dialog_auto import Ui_startovkaDialog
from PyQt4 import QtGui,QtCore
from PyQt4.QtCore import QLocale, QTranslator
import pygame
from pygame import joystick, locals
from ar import ar,fciSort,pointSort
from threading import Timer
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4,landscape, cm
from reportlab.platypus import Image, Paragraph, ParagraphAndImage, SimpleDocTemplate, Table, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus.doctemplate import SimpleDocTemplate
from PIL.TiffImagePlugin import ARTIST
from reportlab.pdfgen import textobject
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.fonts import addMapping

class AgilityRegister(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self )
        self.ui = Ui_MainWindow()
        self.verzia="0.1dev"
        self.ui.setupUi(self)
        #show external display?
        self.showExtDisplay = False
        #inicializujem preteky
        self.preteky = ar()
        self.pdf=PdfExport()
        self.ui.behyTable.setColumnWidth(0, 20)
        self.ui.behyTable.setColumnWidth(1, 75)
        self.ui.behyTable.setColumnWidth(2, 120)
        self.ui.behyTable.setColumnWidth(3, 120)
        
        #nastavenie joysticku
        self.rezim=[0,0]
        self.jbutts=[6,7]
        thread.start_new_thread(joystickThread,(self,1))
        
        pygame.mixer.init()                                              
        pygame.mixer.music.load("scifi-beep-low2.mp3") 

    def confirmQuit(self):
        reply = QtGui.QMessageBox.question(self, 'Message',"Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            pygame.joystick.quit()
            sys.exit(app.exec_())
    def aboutWindow(self):
        QtGui.QMessageBox.about(self,"AgilityRegister "+"Verzia %(verzia)s" % {"verzia":self.verzia}, \
u"AgilityRegister je voľne dostupný softvér distribuovaný v súlade s licečnými podmienkami MIT licencie.\n\n" \
u"POZOR! Softvér je vo vývojovom šťádiu. Nepoužívajte v produkčnom prostredí!.\n\n" \
u"Pripomienky vítané na sorgo@cool.sk\nhttp://code.google.com/p/agilityregister/\n\n" \
u"Užívateľ získava neobmedzené právo kopírovať, používať a modifikovať program, redistribuovať modifikované verzie programu za predpokladu uvedenia autora a informácií o licencii, spolu s upozornením na zrieknutie sa zodpovednosti za dielo. Prijatím tejto licencie sa užívateľ vzdá práva na podanie žaloby na správcu kódu.\n\n"\
u"Copyright © 2011 Sorger Peter\n\n" \
u"Permission is hereby granted, free of charge, to any person obtaining a copy "\
u"of this software and associated documentation files (the \"Software\"), to deal "\
u"in the Software without restriction, including without limitation the rights "\
u"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell "\
u"copies of the Software, and to permit persons to whom the Software is "\
u"furnished to do so, subject to the following conditions:\n\n"\
u"The above copyright notice and this permission notice shall be included in "\
u"all copies or substantial portions of the Software.\n\n"\
u"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR "\
u"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, "\
u"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE "\
u"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER "\
u"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, "\
u"TORT OR OTHERWISE, ARISING FROM, "\
u"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN "\
u"THE SOFTWARE." )
    def vybratPretekyMenu(self):
        Dialog = vybratPretekyDialog()
        dir=dircache.listdir('.')
        for f in dir:
            if (f[-4:]==str('.agi')):
                #print f
                Dialog.ui.listWidget.addItem(f)
#                subory.append(f)
#        suboryM = QtGui.QStringListModel(subory)
        QtCore.QObject.connect(Dialog.ui.pushButton, QtCore.SIGNAL("clicked()"), Dialog.reject)
        QtCore.QObject.connect(Dialog.ui.pushButton_2, QtCore.SIGNAL("clicked()"), Dialog.accept)
        QtCore.QObject.connect(Dialog.ui.pushButton_3, QtCore.SIGNAL("clicked()"), Dialog.accept)
        QtCore.QObject.connect(Dialog.ui.listWidget, QtCore.SIGNAL("itemSelectionChanged()"),Dialog.copyselection)
        Dialog.show()
        ret = Dialog.exec_()
        if ret==1:
            self.zobrazZoznamBehov()
            self.vytvor_menu_behov()
    def udajeEditorMenu(self):
        Dialog = udajeDialog()
        QtCore.QObject.connect(Dialog.ui.fileButton, QtCore.SIGNAL("clicked()"), Dialog.chooseFile)
        Dialog.setData(self.preteky.udaje.get(1))
        Dialog.show()
        ret=Dialog.exec_()
        if ret==1:
            #print Dialog.data
            self.preteky.udaje.set(Dialog.data)
            self.preteky.save_udaje()
            #print self.preteky.udaje.data
            #self.preteky.save_udaje()
    def behyEditorMenu(self):
        Dialog = behyDialog()
        QtCore.QObject.connect(Dialog.ui.pridajButton, QtCore.SIGNAL("clicked()"), Dialog.pridajRiadok)
        QtCore.QObject.connect(Dialog.ui.vymazButton, QtCore.SIGNAL("clicked()"), Dialog.vymazRiadok)
        Dialog.setData(self.preteky.behy.get())
        Dialog.ui.tableWidget.setColumnWidth(0, 20)
        Dialog.ui.tableWidget.setColumnWidth(1, 125)
        Dialog.ui.tableWidget.setColumnWidth(2, 40)
        Dialog.ui.tableWidget.setColumnWidth(3, 80)
        Dialog.ui.tableWidget.setColumnWidth(4, 125)
        Dialog.ui.tableWidget.setColumnWidth(5, 40)
        Dialog.ui.tableWidget.setColumnWidth(6, 50)
        Dialog.ui.tableWidget.setColumnWidth(7, 50)
        Dialog.ui.tableWidget.setColumnWidth(8, 50)
        Dialog.ui.tableWidget.setColumnWidth(9, 60)
        Dialog.show()
        ret=Dialog.exec_()
        if ret==1:
            self.preteky.behy.set(Dialog.data)
            self.preteky.save_behy();
            self.zobrazZoznamBehov()
        #print 'behy exit return'
        #print ret
    def startovkaEditorMenu(self):
        Dialog = startovkaDialog()
        QtCore.QObject.connect(Dialog.ui.pridajButton, QtCore.SIGNAL("clicked()"), Dialog.pridajRiadok)
        QtCore.QObject.connect(Dialog.ui.vymazButton, QtCore.SIGNAL("clicked()"), Dialog.vymazRiadok)
        Dialog.setData(self.preteky.startovka.get())
        Dialog.ui.tableWidget.setColumnWidth(0, 25)
        Dialog.ui.tableWidget.setColumnWidth(1, 40)
        Dialog.ui.tableWidget.setColumnWidth(2, 100)
        Dialog.ui.tableWidget.setColumnWidth(3, 100)
        Dialog.ui.tableWidget.setColumnWidth(4, 125)
        Dialog.ui.tableWidget.setColumnWidth(5, 100)
        Dialog.ui.tableWidget.setColumnWidth(6, 100)
        Dialog.ui.tableWidget.setColumnWidth(7, 35)
        Dialog.ui.tableWidget.setColumnWidth(8, 55)
        Dialog.ui.tableWidget.setColumnWidth(9, 35)
        Dialog.ui.tableWidget.setColumnWidth(10, 90)
        Dialog.ui.tableWidget.setColumnWidth(11, 90)
        Dialog.ui.tableWidget.setColumnWidth(12, 40)
        Dialog.show()
        ret=Dialog.exec_()
        if ret==1:
            print Dialog.data
            self.preteky.startovka.set(Dialog.data)
            self.preteky.save_startovka();
            #self.zobrazZoznamBehov()
    def zobrazZoznamBehov(self):
        self.ui.behyTable.setRowCount(0)
        for beh in self.preteky.behy.get():
            self.ui.behyTable.insertRow(beh[0]-1)
            self.ui.behyTable.setItem(beh[0]-1,0,QtGui.QTableWidgetItem(QtCore.QString(str(beh[0]))))
            self.ui.behyTable.setItem(beh[0]-1,1,QtGui.QTableWidgetItem(QtCore.QString(beh[1][2])))
            self.ui.behyTable.setItem(beh[0]-1,2,QtGui.QTableWidgetItem(QtCore.QString(beh[1][0])))
            self.ui.behyTable.setItem(beh[0]-1,3,QtGui.QTableWidgetItem(QtCore.QString(beh[1][3])))
    def nastavBeh(self):
        if len(self.ui.behyTable.selectedItems())>0:
            beh=int(self.ui.behyTable.item(self.ui.behyTable.selectedItems()[0].row(),0).text())
#            print 'beh: '+str(beh)
#            print self.preteky.behy.data[beh]
            self.preteky.aktualnyBeh=beh
            #print 'nastavujem aktualny beh na '+str(beh)
            self.nacitajBehStartovku()
            self.ui.aktualnyBehLabel.setText(self.preteky.behy.data[beh][2]+" "+self.preteky.behy.data[beh][0]+" ("+str(len(self.preteky.aktualnaStartovka))+")")
            #self.ui.progressBar.setMaximum(self.preteky.behy.data[beh][7])
            #self.ui.stdCas.setMaximum(self.preteky.behy.data[beh][7])
            #self.ui.stdCas.setValue(self.preteky.behy.data[beh][6])
            #self.ui.progressBar.setFormat('%p / '+str(self.preteky.behy.data[beh][7])+'s')
        else:
            QtGui.QMessageBox.information(self, 'Beh',"Vyber zo zoznamu behov!",QtGui.QMessageBox.Ok);
    def nacitajBehStartovku(self):
        filter=self.preteky.behy.get(1)[self.preteky.aktualnyBeh][4]
        self.preteky.aktualnaStartovka={}
        #print "filter: "+filter
        for id,zaznam in self.preteky.startovka.get():
            #print zaznam
            kat=zaznam[0]
            if (len(filter)==1):
                if (filter==kat[0:1]):
                    self.preteky.aktualnaStartovka[id]=zaznam
            elif (len(filter)==3):
                if (filter==kat):
                    self.preteky.aktualnaStartovka[id]=zaznam
        if (len(self.preteky.aktualnaStartovka)>0):
            self.preteky.aktualnyTim=self.preteky.aktualnaStartovka.keys()[0]
            self.nastavTim()
        else:
            self.preteky.aktualnyTim=0
            self.nastavTim()
            QtGui.QMessageBox.information(self,u'Chyba', u'Prázdna štartovka pre beh '+self.preteky.behy.get(1)[self.preteky.aktualnyBeh][0]+' (filter: '+filter+')')
    def nastavTim(self):
        tim=self.preteky.aktualnyTim
        if (tim>0):
            #print self.preteky.aktualnaStartovka[tim]
            self.ui.aktualnyTimLabel.setText(str(tim)+' <span style=" font-weight:600;">'+self.preteky.aktualnaStartovka[tim][1]+' '+self.preteky.aktualnaStartovka[tim][2]+'</span> & '+self.preteky.aktualnaStartovka[tim][4]+' <span style="font-size:10pt;">'+self.preteky.aktualnaStartovka[tim][5]+'</span>')
#TODO zobrazit vysledky, ak su
            vysledok=self.preteky.vysledky.get0(self.preteky.aktualnyBeh, self.preteky.aktualnyTim)
            self.ui.casEdit.setText(QtCore.QString(str(vysledok[2])))
            if (not self.preteky.casomiera.bezim):
                self.preteky.casomiera.cas=vysledok[2]
            self.ui.chybyEdit.setText(QtCore.QString(str(vysledok[3])))
            self.preteky.casomiera.chy=vysledok[3]
            self.ui.odmietnutiaEdit.setText(QtCore.QString(str(vysledok[4])))
            self.preteky.casomiera.odm=vysledok[4]
            tb=vysledok[6]
            self.ui.TBLabel.setText(QtCore.QString(str(tb)))
            if (tb==200):
                self.ui.nestButton.setChecked(True)
                self.ui.TBLabel.setText(QtCore.QString('-'))
            else:
                self.ui.nestButton.setChecked(False)
            if (tb==100):
                self.ui.nestButton_2.setChecked(True)
                self.ui.TBLabel.setText(QtCore.QString('-'))
            else:
                self.ui.nestButton_2.setChecked(False)
        else:
            self.ui.aktualnyTimLabel.setText('<span style=" font-size:8px;">-</span>')
#TODO nastavit zadavanie vysledkov na disabled
    def nextTim(self):
        oldTim=self.preteky.aktualnyTim
        zabrejkuj=False
        if (oldTim>0):
            for tim in self.preteky.aktualnaStartovka.iteritems():
                if zabrejkuj==True:
                    self.preteky.aktualnyTim=tim[0]
                    self.nastavTim()
                    break
                if oldTim==tim[0]:
                    zabrejkuj=True
                
    def prevTim(self):
        oldTim=self.preteky.aktualnyTim
        prev=oldTim;
        if (oldTim>0):
            for tim in self.preteky.aktualnaStartovka.iteritems():
                if oldTim==tim[0]:
                    self.preteky.aktualnyTim=prev
                    self.nastavTim()
                prev=tim[0]
    def startStop(self, speak=False):
        if (self.preteky.casomiera.bezim):
            self.t.cancel()
            pygame.mixer.music.play()
            self.preteky.casomiera.bezim=False
            self.preteky.casomiera.cas=time.time()-self.preteky.casomiera.cas0
            self.ui.label.setText(str(self.preteky.casomiera.cas))
            #print str(self.preteky.casomiera.cas)
            self.showTime(self.preteky.casomiera.cas)
            self.ui.stopButton.setText(u'ŠTART')
            self.ui.stopButton.setChecked(False)
            #thread.start_new_thread(myfunction,("1",self.ui,2))
            self.copyTime()
            if speak:
                self.speak(self.preteky.casomiera.cas)
                jazyk=self.preteky.aktualnaStartovka[self.preteky.aktualnyTim][11]

                
                if jazyk=='hu':
                    self.speak(self.preteky.casomiera.cas,'hu')
#                elif jazyk=='cz':
#                   self.speak(self.preteky.casomiera.cas,'cs')
                elif jazyk=='fr':
                    self.speak(self.preteky.casomiera.cas,'fr')
        else:
            pygame.mixer.music.play()
            self.preteky.casomiera.bezim=True
            self.preteky.casomiera.cas0=time.time()
            self.t=Timer(0.1,self.rewriteTime)
            self.t.start()
            self.ui.stopButton.setText(u'STOP')
            self.ui.stopButton.setChecked(True)
    def speak(self, cas, jazyk='sk'):
        #sekundy="%(sekundy)02d" % {"sekundy" : int(round(cas))}
        sekundy="%(sekundy)d" % {"sekundy":math.floor(cas)}
        stotiny="%(stotiny)02d" % {"stotiny": round((cas-math.floor(cas))*100)}
        if stotiny=="00":
            if jazyk=='sk':
                stotiny="presne"
            if jazyk=='hu':
                stotiny='pontosan'
        text=sekundy+' '+stotiny
        #cmd='call "C:\Program Files (x86)\eSpeak\command_line\espeak.exe" -v '+jazyk+' -s 160 -p 40 "'+text+'"'+
        cmd='espeak -v '+jazyk+' -s 160 -p 40 "'+text+'"'
        print cmd
        os.popen(cmd)
    def showTime(self, cas):
        sekundy=math.floor(cas)
        stotiny=round((cas-sekundy)*100)
        text="%(sekundy)03d.%(stotiny)02d" % {'sekundy':sekundy, 'stotiny':stotiny}
        self.ui.label.setText(text)
    def rewriteTime(self):
        roundg=10
        if (self.preteky.casomiera.bezim):
            self.showTime(round((time.time()-self.preteky.casomiera.cas0)*roundg)/roundg)
            self.t=Timer(1/roundg,self.rewriteTime)
            self.t.start()
        self.rewriteTB()
    def rewriteTB(self):
        roundg=100
        self.preteky.casomiera.tb=(self.preteky.casomiera.chy+self.preteky.casomiera.odm)*5
        if (self.preteky.casomiera.bezim):
            if (time.time()-self.preteky.casomiera.cas0>self.preteky.behy.data[self.preteky.aktualnyBeh][6]):
                self.preteky.casomiera.tb+=(round((time.time()-self.preteky.casomiera.cas0)*roundg)/roundg)-self.preteky.behy.data[self.preteky.aktualnyBeh][6]
        else:
            if (self.preteky.casomiera.cas>self.preteky.behy.data[self.preteky.aktualnyBeh][6]):
                self.preteky.casomiera.tb+=(round((self.preteky.casomiera.cas)*roundg)/roundg)-self.preteky.behy.data[self.preteky.aktualnyBeh][6]
        self.ui.TBLabel.setText(str(round(self.preteky.casomiera.tb*100)/100))
            #self.ui.progressBar.setValue(round(time.time()-self.preteky.casomiera.cas0))
    def copyTime(self):
        self.ui.casEdit.setText(str(round(self.preteky.casomiera.cas*1000)/1000))
    def chybaPlus(self):
        chyb=int(self.ui.chybyEdit.text())+1
        self.preteky.casomiera.chy=chyb
        self.ui.chybyEdit.setText(QtCore.QString(str(chyb)))
        self.rewriteTB()
    def chybaMinus(self):
        chyb=int(self.ui.chybyEdit.text())-1
        if chyb<0:
            chyb=0
        self.preteky.casomiera.chy=chyb
        self.ui.chybyEdit.setText(QtCore.QString(str(chyb)))
        self.rewriteTB()
    def odmPlus(self):
        odm=int(self.ui.odmietnutiaEdit.text())+1
        self.ui.odmietnutiaEdit.setText(QtCore.QString(str(odm)))
        if (odm>=3):
            self.ui.nestButton_2.setChecked(True)
        self.preteky.casomiera.odm=odm
        self.rewriteTB()
    def odmMinus(self):
        odm=int(self.ui.odmietnutiaEdit.text())-1
        if odm<0:
            odm=0
        self.ui.odmietnutiaEdit.setText(QtCore.QString(str(odm)))
        self.preteky.casomiera.odm=odm
        self.rewriteTB()
    def ulozVysledok(self):
        nest=self.ui.nestButton.isChecked()
        dis=self.ui.nestButton_2.isChecked()
        if (self.ui.TBLabel.text()=='-'):
            self.ui.TBLabel.setText('0')
        self.preteky.setVysledok(self.preteky.aktualnyBeh, self.preteky.aktualnyTim, float(self.ui.casEdit.text()), \
            int(self.ui.chybyEdit.text()), int(self.ui.odmietnutiaEdit.text()), \
            float(self.ui.TBLabel.text())-(int(self.ui.odmietnutiaEdit.text())+int(self.ui.chybyEdit.text()))*5, nest, dis, True)
    def exportVysledkyBehu(self):
        self.ulozVysledok()
        self.preteky.finalizeVysledky(self.preteky.aktualnyBeh)
    def pdfStartovka(self):
        self.pdf.startovka(self.preteky.udaje.get(1),self.preteky.startovka.get(2))
    def pdfPrezencka(self):
        self.pdf.prezencka(self.preteky.udaje.get(1),self.preteky.startovka.get(0))
    def pdfStatistika(self):
        self.pdf.statistika(self.preteky.udaje.get(1),self.preteky.startovka.get(0))
    def pdfZapis(self):
        self.pdf.zapis(self.preteky.udaje.get(1),self.preteky.startovka.get(0))
    def pdfVysledok(self,beh):
        self.pdf.vysledky(beh,self.preteky)
    def pdfVitazi(self):
        self.pdf.vitazi(self.preteky)
    def pdfVZ(self):
        self.pdf.vz(self.preteky)
    def pdfVysledokSucet(self,sucet):
        print 'vysledok sucet'+str(sucet)
        self.pdf.vysledkySucet(sucet, self.preteky)
    def vytvor_menu_behov(self):
        #print 'vytvor menu behov'
        self.ui.menuJednotliv_behy.clear()
        self.ui.menuS_ty.clear()
        behy=self.preteky.behy.get(0)
        sucty=self.preteky.sucty.get(0)
        #self.ui.menuV_sledky.addSeparator()
        for b in behy:
            #print str(b[0])+' '+b[1][0]+' '+b[1][2]
            vars(self.ui)['actionBeh'+str(b[0])]=QtGui.QAction(self)
            vars(self.ui)['actionBeh'+str(b[0])].setObjectName(QtCore.QString.fromUtf8("actionBeh"+str(b[0])))
            self.ui.menuJednotliv_behy.addAction(vars(self.ui)['actionBeh'+str(b[0])])
            vars(self.ui)['actionBeh'+str(b[0])].setText(QtGui.QApplication.translate("MainWindow", b[1][2]+' '+b[1][0], None, QtGui.QApplication.UnicodeUTF8))
            self.connect(vars(self.ui)['actionBeh'+str(b[0])],QtCore.SIGNAL("triggered()"),lambda bp=b[0] : f.pdfVysledok(bp))
        for b in sucty:
            #print b
            #print str(b[0])+' '+b[1][0]+' '+b[1][2]
            vars(self.ui)['actionSucet'+str(b[0])]=QtGui.QAction(self)
            vars(self.ui)['actionSucet'+str(b[0])].setObjectName(QtCore.QString.fromUtf8("actionSucet"+str(b[0])))
            self.ui.menuS_ty.addAction(vars(self.ui)['actionSucet'+str(b[0])])
            vars(self.ui)['actionSucet'+str(b[0])].setText(QtGui.QApplication.translate("MainWindow", b[1][0], None, QtGui.QApplication.UnicodeUTF8))
            self.connect(vars(self.ui)['actionSucet'+str(b[0])],QtCore.SIGNAL("triggered()"),lambda bp=b[0] : f.pdfVysledokSucet(bp))
    def swapRezim(self):
        rezimy=[[0,0],[0,1],[1,0],[1,1]]
        nazvyrezimov=['A->A','A->B','B->A','B->B']
        aktualnyrezim=-1
        for k,r in enumerate(rezimy):
            print k,r
            if r==self.rezim:
                aktualnyrezim=k
        aktualnyrezim+=1
        if aktualnyrezim>len(rezimy)-1:
            aktualnyrezim=0
        self.rezim=rezimy[aktualnyrezim]
        self.ui.resetButton.setText(nazvyrezimov[aktualnyrezim]) 
class behyDialog(QtGui.QDialog):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_behyDialog()
        self.ui.setupUi(self)
    def reject(self):
        self.hide()
        self.done(0)
    def accept(self):
        #(1, u'Sk\xfa\u0161ka SA1', u'SA1', u'28.5.2011', u'Nalle Jansson', u'SA1', 160.0, 50.0, 90.0, 16, 123)
        #print self.ui.tableWidget.rowCount()
        self.data=[]
        for riadok in range(0,self.ui.tableWidget.rowCount()):
            novyriadok=()
            for stlpec in range(0,10):
                tmpdata=self.ui.tableWidget.item(riadok, stlpec).text();
                if stlpec in [0,9]:
                    tmpdata=int(tmpdata)
                elif stlpec in [6,7,8]:
                    tmpdata=float(tmpdata)
                else:
                    tmpdata=unicode(tmpdata)
                novyriadok+=(tmpdata,)
                #print self.ui.tableWidget.item(riadok, stlpec).text()
            novyriadok+=(0,)
            self.data.append(novyriadok)
            #print tmpdata
#        self.data=(('nazov',unicode(self.ui.nazov.text())),\
        #print 'vysledok:'
        #print self.data
        self.hide()
        self.done(1)
    def pridajRiadok(self):
        riadok=self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(riadok)
        #id
        self.ui.tableWidget.setItem(riadok,0,QtGui.QTableWidgetItem(QtCore.QString(str(riadok+1))))
        #nazov 
        self.ui.tableWidget.setItem(riadok,1,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        #typ
        self.ui.tableWidget.setItem(riadok,2,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        #datum
        self.ui.tableWidget.setItem(riadok,3,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        #rozhodca
        self.ui.tableWidget.setItem(riadok,4,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        #filter
        self.ui.tableWidget.setItem(riadok,5,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        #dlzka
        self.ui.tableWidget.setItem(riadok,6,QtGui.QTableWidgetItem(QtCore.QString("0"))) 
        #st cas
        self.ui.tableWidget.setItem(riadok,7,QtGui.QTableWidgetItem(QtCore.QString("0"))) 
        #max cas
        self.ui.tableWidget.setItem(riadok,8,QtGui.QTableWidgetItem(QtCore.QString("0"))) 
        #pocet prekazok
        self.ui.tableWidget.setItem(riadok,9,QtGui.QTableWidgetItem(QtCore.QString("0"))) 
    def vymazRiadok(self):
        if (self.ui.tableWidget.selectedIndexes()<>[]):
            #print self.ui.tableWidget.selectedIndexes()[0].row()
            self.ui.tableWidget.removeRow(self.ui.tableWidget.selectedIndexes()[0].row())
    def setData(self,data):
        #print 'nastavujem udaje'
        #print data
        for k,row in data:
            #print 'k'+str(k)
            self.ui.tableWidget.insertRow(int(k)-1)
            qitem = QtGui.QTableWidgetItem(QtCore.QString(str(k)));
            self.ui.tableWidget.setItem(int(k)-1,0,qitem)
            i=1
            for item in row:
                qitem = QtGui.QTableWidgetItem(QtCore.QString(item if type(item)==unicode else str(item)));
                #print 'zapisujem do tabulky'
                #print str(int(k)-1)+'x'+str(i)
                #print item
                #print type(item)
                self.ui.tableWidget.setItem(int(k)-1,i,qitem)
                i+=1
class startovkaDialog(QtGui.QDialog):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_startovkaDialog()
        self.ui.setupUi(self)
    def reject(self):
        self.hide()
        self.done(0)
    def accept(self):
        #(1, u'Sk\xfa\u0161ka SA1', u'SA1', u'28.5.2011', u'Nalle Jansson', u'SA1', 160.0, 50.0, 90.0, 16, 123)
        #print self.ui.tableWidget.rowCount()
        self.data=[]
        for riadok in range(0,self.ui.tableWidget.rowCount()):
            novyriadok=()
            for stlpec in range(0,13):
                tmpdata=self.ui.tableWidget.item(riadok, stlpec).text();
                if stlpec in [0]:
                    tmpdata=int(tmpdata)
                elif stlpec in [7,9]:
                    print tmpdata
                    if tmpdata<>"" or tmpdata=="0":
                        tmpdata=1
                    else:
                        tmpdata=""
                else:
                    tmpdata=unicode(tmpdata)
                novyriadok+=(tmpdata,)
                #print self.ui.tableWidget.item(riadok, stlpec).text()
            #novyriadok+=(0,)
            self.data.append(novyriadok)
            #print tmpdata
#        self.data=(('nazov',unicode(self.ui.nazov.text())),\
        #print 'vysledok:'
        #print self.data
        self.hide()
        self.done(1)
    def pridajRiadok(self):
        riadok=self.ui.tableWidget.rowCount()
        maxid=0
        print "------------"
        for rowid in range(riadok):
            print 'porovnavam'
            print "maxid"
            print maxid
            print "rowid "+str(rowid)
            print int(self.ui.tableWidget.item(rowid, 0).text())
            if (maxid<int(self.ui.tableWidget.item(rowid, 0).text())):
                maxid=int(self.ui.tableWidget.item(rowid, 0).text())
        self.ui.tableWidget.insertRow(riadok)
        #id
        print 'maxid: '+str(maxid)
        #self.ui.tableWidget.setItem(riadok,0,QtGui.QTableWidgetItem(QtCore.QString(str(riadok+1))))
        self.ui.tableWidget.setItem(riadok,0,QtGui.QTableWidgetItem(QtCore.QString(str(maxid+1))))
        self.ui.tableWidget.setItem(riadok,1,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,2,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,3,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,4,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,5,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,6,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,7,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,8,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,9,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,10,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,11,QtGui.QTableWidgetItem(QtCore.QString(""))) 
        self.ui.tableWidget.setItem(riadok,12,QtGui.QTableWidgetItem(QtCore.QString(""))) 

    def vymazRiadok(self):
        if (self.ui.tableWidget.selectedIndexes()<>[]):
            #print self.ui.tableWidget.selectedIndexes()[0].row()
            self.ui.tableWidget.removeRow(self.ui.tableWidget.selectedIndexes()[0].row())
    def setData(self,data):
        #print 'nastavujem udaje'
        #print data
        rowi=0
        for k,row in data:
            #print 'k'+str(k)
            self.ui.tableWidget.insertRow(rowi)
            qitem = QtGui.QTableWidgetItem(QtCore.QString(str(k)));
            self.ui.tableWidget.setItem(rowi,0,qitem)
            i=1
            for item in row:
                qitem = QtGui.QTableWidgetItem(QtCore.QString(item if type(item)==unicode else str(item)));
                #print 'zapisujem do tabulky'
                #print str(int(k)-1)+'x'+str(i)
                #print item
                #print type(item)
                self.ui.tableWidget.setItem(rowi,i,qitem)
                i+=1
            rowi+=1

def joystickThreadX(ar,*args):
    pygame.init()
    pygame.joystick.init()
    mamj=False
    while 1:
        try:
            j
            mamj=True
            #print string
            for e in pygame.event.get(): # iterate over event stack
                pprint.pprint(e)
                print e
                print 'event : ' + str(e.type)
                if e.type == pygame.locals.JOYAXISMOTION: # 7
                    x , y = j.get_axis(0), j.get_axis(1)
                    #print 'x and y : ' + str(x) +' , '+ str(y)
                elif e.type == pygame.locals.JOYBALLMOTION: # 8
                    print 'ball motion'
                elif e.type == pygame.locals.JOYHATMOTION: # 9
                    print 'hat motion'
                elif e.type == pygame.locals.JOYBUTTONDOWN: # 10
                    print 'button down'
                elif e.type == pygame.locals.JOYBUTTONUP: # 11
                    print 'button up'
            time.sleep(0.005)
        except NameError:
            mamj=False
            try:
                pygame.init()
                pygame.joystick.init()
                j = pygame.joystick.Joystick(0) # create a joystick instance
                j.init() # init instance
                print 'Enabled joystick: ' + j.get_name()
                mamj=True
                #TODO nastavit vizual
            except pygame.error:
                mamj=False
                print 'no nemam ;)'
                #TODO nastavit vizual
        time.sleep(0.005 if mamj else 1)

def joystickThread(ar,*args):
    pygame.init()
    pygame.joystick.init()
    try:
        j = pygame.joystick.Joystick(0) # create a joystick instance
        j.init() # init instance
        #print 'Enabled joystick: ' + j.get_name()
    except pygame.error:
        print 'no joystick found.'
    cas0=time.time()
    while 1:
        for e in pygame.event.get(): # iterate over event stack
            #print 'event : ' + str(e.type)
            #print e
#            if e.type == pygame.locals.JOYAXISMOTION: # 7
#                x , y = j.get_axis(0), j.get_axis(1)
                #print 'x and y : ' + str(x) +' , '+ str(y)
            #elif e.type == pygame.locals.JOYBALLMOTION: # 8
                #print 'ball motion'
            #elif e.type == pygame.locals.JOYHATMOTION: # 9
                #print 'hat motion'
            if e.type == pygame.locals.JOYBUTTONDOWN: # 10
                #print ar.rezim
                if ar.preteky.casomiera.bezim:
                    if e.button==ar.jbutts[ar.rezim[1]] and cas0+2<time.time():
                        ar.startStop(True)
                        time.sleep(0.1)
                        cas0=time.time()
                else:
                    if e.button==ar.jbutts[ar.rezim[0]]:
                        ar.startStop(True)
                        time.sleep(0.1)
                        cas0=time.time()
                
                #print e.button
                #print 'button down'
            #elif e.type == pygame.locals.JOYBUTTONUP: # 11
                #print e.button
                #print 'button up'
        time.sleep(0.005)

class udajeDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_udajeDialog()
        self.ui.setupUi(self)
        self.logo=''
    def chooseFile(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Logo','.')
        #print filename
        self.ui.logoView.setPixmap(QtGui.QPixmap(filename))
        self.logo=filename
        #self.textEdit.setText(data)
    def setData(self,data):
        #print 'nastavujem udaje'
        #print data
        self.ui.nazov.setText(data['nazov'])
        self.ui.datum.setText(data['datum'])
        self.ui.organizator.setText(data['organizator'])
        self.ui.garant.setText(data['garant'])
        self.ui.rozhodca.setText(data['rozhodca'])
        if (data['logo']<>""):
            self.ui.logoView.setPixmap(QtGui.QPixmap(data['logo']))
            self.logo=data['logo']
    def reject(self):
        self.hide()
        self.done(0)
    def accept(self):
        self.data=(('nazov',unicode(self.ui.nazov.text())),\
                   ('datum',unicode(self.ui.datum.text())),\
                   ('organizator',unicode(self.ui.organizator.text())),\
                   ('garant',unicode(self.ui.garant.text())),\
                   ('rozhodca',unicode(self.ui.rozhodca.text())),\
                   ('logo',unicode(self.logo)))
        #print 'nacitane udaje'
        #print self.data
        self.hide()
        self.done(1)

class vybratPretekyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_vybrat_preteky_dialog()
        self.ui.setupUi(self)
    def reject(self):
        self.hide()
        self.done(0)
    def accept(self):
        fname=str(self.ui.lineEdit.text())
        #print self.ui.listWidget.selectedItems()[0].text()
        if (fname<>''):
            f.preteky.load(fname)
            self.hide()
            self.done(1)
    def copyselection(self):
        self.ui.lineEdit.setText(self.ui.listWidget.selectedItems()[0].text())
        #print self.ui.listWidget.SelectItems
    

class ARTemplate(SimpleDocTemplate):
    def onFirstPage(self, canvas, document):
        pdfmetrics.registerFont(TTFont('Ubuntu', 'font/Ubuntu-R.ttf'))
        pdfmetrics.registerFont(TTFont('Ubuntu-Bold', 'font/Ubuntu-B.ttf'))
        pdfmetrics.registerFont(TTFont('Ubuntu-Italic', 'font/Ubuntu-I.ttf'))
        pdfmetrics.registerFont(TTFont('Ubuntu-BI', 'font/Ubuntu-BI.ttf'))
        #canvas.line(canvas._pagesize[0]-5,5,canvas._pagesize[0]-5,canvas._pagesize[1]-50)
        try:
            logo = Image(self.udaje['logo'])
        except IOError:
            #TODO vytvorit nologo.jpg
            logo = Image('logo2011.jpg')
        ih=4*cm*logo.drawHeight/logo.drawWidth
        canvas.drawImage(self.udaje['logo'],canvas._pagesize[0]-5*cm,canvas._pagesize[1]-5*cm+(4*cm-ih),4*cm,ih)
        nadpis=canvas.beginText()
        nadpis.setTextOrigin(cm,canvas._pagesize[1]-1*cm-18) 
        nadpis.setFont('Ubuntu-Bold', 18)
        nadpis.textLine(self.nazov)
        nadpis.setFont('Ubuntu-Bold', 14)
        nadpis.textLine(self.udaje['nazov'])
        nadpis.setFont('Ubuntu', 12)
        nadpis.textLine(self.udaje['datum'])
        canvas.drawText(nadpis)
        self.footerTime(canvas)
    def onLaterPages(self,canvas,document):
        nadpis=canvas.beginText()
        nadpis.setTextOrigin(cm,canvas._pagesize[1]-1*cm) 
        nadpis.setFont('Ubuntu', 12)
        nadpis.textLine(self.nazov+' // '+self.udaje['nazov']+' // '+self.udaje['datum'])
        canvas.drawText(nadpis)
        self.footerTime(canvas)
    def footerTime(self, canvas):
        nadpis=canvas.beginText()
        nadpis.setTextOrigin(cm,cm)
        nadpis.setFont('Ubuntu', 8)
        nadpis.textLine('Spracované: '+time.strftime('%d.%m.%y %H:%M:%S'))
        canvas.drawText(nadpis) 

class ARTemplateVZ(SimpleDocTemplate):
    def onFirstPage(self, canvas, document):
        pdfmetrics.registerFont(TTFont('Ubuntu', 'font\Ubuntu-R.ttf'))
        pdfmetrics.registerFont(TTFont('Ubuntu-Bold', 'font\Ubuntu-B.ttf'))
        pdfmetrics.registerFont(TTFont('Ubuntu-Italic', 'font\Ubuntu-I.ttf'))
        pdfmetrics.registerFont(TTFont('Ubuntu-BI', 'font\Ubuntu-BI.ttf'))
        #canvas.line(canvas._pagesize[0]-5,5,canvas._pagesize[0]-5,canvas._pagesize[1]-50)

class PdfExport():
    execstr='gnome-open'

    def startovka(self,udaje,startovka):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        doc = ARTemplate("startovka.pdf", pagesize=A4,
                                rightMargin=1*cm,leftMargin=1*cm,
                                topMargin=1*cm,bottomMargin=1.5*cm)
        doc.udaje=udaje
        doc.nazov='Štartovná listina'
        style = getSampleStyleSheet()
        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=12
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=-0.2*cm
        style['Heading1'].firstLineIndent=0
        tableStyle=[('GRID',(0,0),(-1,-1),0.3,colors.black),
                    ('BACKGROUND',(0,0),(-1,0),colors.lightgrey),
                    ('FONT', (0,0), (-1,0), 'Ubuntu-Bold'),
                    ('FONT', (0,1), (-1,-1), 'Ubuntu'),
                    ('FONTSIZE',(0,0),(-1,0), 8),
                    ('FONTSIZE',(0,0),(-1,-1), 7),
                    ('LEFTPADDING',(0,0),(-1,-1), 3),
                    ('TOPPADDING',(0,0),(-1,-1), 1),
                    ('RIGHTPADDING',(0,0),(-1,-1), 3),
                    ('BOTTOMPADDING',(0,0),(-1,-1), 0),
                    ('ROWBACKGROUNDS',(0,1),(-1,-1), (None,0xE0E0E0)),
                    #('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    #('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    #('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    #('BOX',(0,0),(-1,-1),2,colors.black),
                    #('GRID',(0,0),(-1,-1),0.5,colors.black),
                    ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                    #('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    #('BACKGROUND',(3,1),(3,1),colors.khaki),
                    #('ALIGN',(3,1),(3,1),'CENTER'),
                    #('BACKGROUND',(3,2),(3,2),colors.beige),
                    #('ALIGN',(3,2),(3,2),'LEFT'),
                    ]
        # container for the 'Flowable' objects
        elements = [Spacer(1, cm*2.5)]
        kat=""
        tableHeader=(u'Č.',u'Kat.',u'Meno psovoda',u'Klub',u'Meno psa',u'Plemeno',u'')
        colWidths=[0.5*cm, 0.9*cm, 4*cm, 3.7*cm, 5.4*cm, 4*cm, 0.5*cm]
        katNadpis='Kategória'
        Kstartovka=[tableHeader]
        for zaznam in startovka:
            #print zaznam
            currkat=zaznam[1][0:1]
            if currkat=='S':
                currkat='Small'
            elif currkat=='M':
                currkat='Medium'
            else:
                currkat='Large'
            if (currkat<>kat):
                if kat<>'':
                    elements.append(Paragraph(katNadpis+' <b>'+kat+'</b>',style=style['Heading1']))
                    t=Table(Kstartovka,style=tableStyle,repeatRows=1)
                    t._argW=colWidths
                    elements.append(t)
                    Kstartovka=[tableHeader]
                kat=currkat
            I = Image("../icons/flags_iso/48/%(flag)s.png" % {"flag":zaznam[6]})
            I.drawHeight = 0.3*cm*I.drawHeight / I.drawWidth
            I.drawWidth = 0.3*cm
            Kstartovka.append(list((zaznam[0],zaznam[1],zaznam[2],zaznam[3],zaznam[4],zaznam[5],I)))
        elements.append(Paragraph(katNadpis+' <b>'+kat+'</b>',style=style['Heading1']))
        t=Table(Kstartovka,style=tableStyle,repeatRows=1)
        #t.normalizeData(startovka)
        # $w=array(7,7,40,35,45,40,7);
        # $c=array("C","C","L","L","L","L","L","C","C","R","R","R","C","C");

        t._argW=colWidths
        elements.append(t)
        doc.build(elements)
        os.popen(self.execstr+' startovka.pdf')

    def prezencka(self,udaje,startovka):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        doc = ARTemplate("prezentacia.pdf", pagesize=A4,
                                rightMargin=1*cm,leftMargin=1*cm,
                                topMargin=1*cm,bottomMargin=1.5*cm)
        doc.udaje=udaje
        doc.nazov='Prezenčná listina'
        style = getSampleStyleSheet()
        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=10
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=-0.2*cm
        style['Heading1'].firstLineIndent=0
        tableStyle=[('GRID',(0,0),(-1,-1),0.3,colors.black),
                    ('BACKGROUND',(0,0),(-1,0),colors.lightgrey),
                    ('FONT', (0,0), (-1,0), 'Ubuntu-Bold'),
                    ('FONT', (0,1), (-1,-1), 'Ubuntu'),
                    ('FONTSIZE',(0,0),(-1,0), 8),
                    ('FONTSIZE',(0,0),(-1,-1), 7),
                    ('LEFTPADDING',(0,0),(-1,-1), 3),
                    ('TOPPADDING',(0,0),(-1,-1), 1),
                    ('RIGHTPADDING',(0,0),(-1,-1), 3),
                    ('BOTTOMPADDING',(0,0),(-1,-1), 0),
                    ('ROWBACKGROUNDS',(0,1),(-1,-1), (None,0xE0E0E0)),
                    #('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    #('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    #('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    #('BOX',(0,0),(-1,-1),2,colors.black),
                    #('GRID',(0,0),(-1,-1),0.5,colors.black),
                    ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                    #('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    #('BACKGROUND',(3,1),(3,1),colors.khaki),
                    #('ALIGN',(3,1),(3,1),'CENTER'),
                    #('BACKGROUND',(3,2),(3,2),colors.beige),
                    #('ALIGN',(3,2),(3,2),'LEFT'),
                    ]
        # container for the 'Flowable' objects
        elements = [Spacer(1, cm*2.5)]
        kat=""
        tableHeader=(u'Č.',u'Kat.',u'Meno psovoda',u'Klub',u'Pes',u'Merať',u'VZ')
        colWidths=[0.5*cm, 0.9*cm, 3.2*cm, 3.7*cm, 6.2*cm, 2*cm, 2.5*cm]
        katNadpis='Kategória'
        Kstartovka=[tableHeader]
        print startovka
        for zaznam in startovka:
            cislo=zaznam[0]
            zaznam=zaznam[1]
            print zaznam
            currkat=zaznam[0][0:1]
            if currkat=='S':
                currkat='Small'
            elif currkat=='M':
                currkat='Medium'
            else:
                currkat='Large'
            if (currkat<>kat):
                if kat<>'':
                    elements.append(Paragraph(katNadpis+' <b>'+kat+'</b>',style=style['Heading1']))
                    t=Table(Kstartovka,style=tableStyle,repeatRows=1)
                    t._argW=colWidths
                    elements.append(t)
                    Kstartovka=[tableHeader]
                kat=currkat
            Kstartovka.append(list((cislo,zaznam[0],zaznam[1]+' '+zaznam[2],zaznam[3],zaznam[4]+', '+zaznam[5],zaznam[8],zaznam[7])))
        elements.append(Paragraph(katNadpis+' <b>'+kat+'</b>',style=style['Heading1']))
        t=Table(Kstartovka,style=tableStyle,repeatRows=1)
        #t.normalizeData(startovka)
        # $w=array(7,7,40,35,45,40,7);
        # $c=array("C","C","L","L","L","L","L","C","C","R","R","R","C","C");

        t._argW=colWidths
        elements.append(t)
        doc.build(elements)
        os.popen(self.execstr+' prezentacia.pdf')

    def zapis(self,udaje,startovka):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        doc = ARTemplate("zapis.pdf", pagesize=landscape(A4),
                                rightMargin=1*cm,leftMargin=1*cm,
                                topMargin=1*cm,bottomMargin=1.5*cm)
        doc.udaje=udaje
        doc.nazov='Beh: __________ Zapisovateľ: ___________'
        style = getSampleStyleSheet()
        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=10
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=0*cm
        style['Heading1'].firstLineIndent=0
        tableStyle=[('GRID',(0,0),(-1,-1),0.3,colors.black),
                    ('BACKGROUND',(0,0),(-1,0),colors.lightgrey),
                    ('FONT', (0,0), (-1,0), 'Ubuntu-Bold'),
                    ('FONT', (0,1), (-1,-1), 'Ubuntu'),
                    ('FONTSIZE',(0,0),(-1,0), 8),
                    ('FONTSIZE',(0,0),(-1,-1), 6.5),
                    ('LEFTPADDING',(0,0),(-1,-1), 3),
                    ('TOPPADDING',(0,0),(-1,-1), 3),
                    ('RIGHTPADDING',(0,0),(-1,-1), 3),
                    ('BOTTOMPADDING',(0,0),(-1,-1), 3),
                    ('ROWBACKGROUNDS',(0,1),(-1,-1), (None,0xE0E0E0)),
                    #('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    #('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    #('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    #('BOX',(0,0),(-1,-1),2,colors.black),
                    #('GRID',(0,0),(-1,-1),0.5,colors.black),
                    ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                    #('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    #('BACKGROUND',(3,1),(3,1),colors.khaki),
                    #('ALIGN',(3,1),(3,1),'CENTER'),
                    #('BACKGROUND',(3,2),(3,2),colors.beige),
                    #('ALIGN',(3,2),(3,2),'LEFT'),
                    ]
        # container for the 'Flowable' objects
        elements = [Spacer(1, cm*2.5)]
        kat=""
        tableHeader=(u'Č.',u'Kat.',u'Meno psovoda',u'Klub',u'Pes',u'Chyby',u'Odmietnutia',u'Čas')
        colWidths=[0.5*cm, 0.9*cm, 3.2*cm, 3.2*cm, 5.5*cm, 5*cm, 5*cm, 5*cm]
        katNadpis='Kategória'
        Kstartovka=[tableHeader]
        print startovka
        for zaznam in startovka:
            cislo=zaznam[0]
            zaznam=zaznam[1]
            print zaznam
            currkat=zaznam[0][0:1]
            if currkat=='S':
                currkat='Small'
            elif currkat=='M':
                currkat='Medium'
            else:
                currkat='Large'
            if (currkat<>kat):
                if kat<>'':
                    elements.append(Paragraph(katNadpis+' <b>'+kat+'</b>',style=style['Heading1']))
                    t=Table(Kstartovka,style=tableStyle,repeatRows=1)
                    t._argW=colWidths
                    elements.append(t)
                    elements.append(PageBreak())
                    Kstartovka=[tableHeader]
                kat=currkat
            Kstartovka.append(list((cislo,zaznam[0],zaznam[1]+' '+zaznam[2],zaznam[3],zaznam[4]+'\n'+zaznam[5],'','','')))
        elements.append(Paragraph(katNadpis+' <b>'+kat+'</b>',style=style['Heading1']))
        t=Table(Kstartovka,style=tableStyle,repeatRows=1)
        #t.normalizeData(startovka)
        # $w=array(7,7,40,35,45,40,7);
        # $c=array("C","C","L","L","L","L","L","C","C","R","R","R","C","C");

        t._argW=colWidths
        elements.append(t)
        doc.build(elements)
        os.popen(self.execstr+' zapis.pdf')


    def statistika(self,udaje,startovka):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        doc = ARTemplate("statistika.pdf", pagesize=A4,
                                rightMargin=1*cm,leftMargin=1*cm,
                                topMargin=1*cm,bottomMargin=1.5*cm)
        doc.udaje=udaje
        doc.nazov='Štatistika'
        style = getSampleStyleSheet()
        style['Normal'].fontName='Ubuntu'

        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=12
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=-0.2*cm
        style['Heading1'].firstLineIndent=0
        
        # container for the 'Flowable' objects
        elements = [Spacer(1, cm*2.5)]
        
        vt={"S":"Small", "M":"Medium", "L":"Large"}
        
        velkosti={}
        vykonnosti={}
        kluby={}
        plemena={}
        krajiny={}
        pp={0:0, 1:0}
        
        for zaznam in startovka:
            print zaznam
            z=zaznam[1]
            velkost=vt[z[0][0:1]]
            vykonnost=z[0][1:3]
            klub=z[3]
            plemeno=z[5]
            ppp=z[6]
            if ppp=='':
                ppp=0
            krajina=z[11]
            try:
                velkosti[velkost]+=1
            except KeyError:
                velkosti[velkost]=1
            try:
                vykonnosti[vykonnost]+=1
            except KeyError:
                vykonnosti[vykonnost]=1
            try:
                kluby[klub]+=1
            except KeyError:
                kluby[klub]=1
            try:
                plemena[plemeno]+=1
            except KeyError:
                plemena[plemeno]=1
            try:
                krajiny[krajina]+=1
            except KeyError:
                krajiny[krajina]=1
            pp[ppp]+=1
        
        print velkosti, vykonnosti, kluby, plemena, pp
        
        
        #velkosti        
        spolu=sum(velkosti.values())
        txt='<b>Veľkostné kategórie</b>'
        elements.append(Paragraph(txt,style=style['Heading1']))
        txt=''
        for i in velkosti:
            txt+=i+': <b>%(pocet)d</b> (%(percenta)0.1f%%) ' % {'pocet':velkosti[i], 'percenta': float(velkosti[i])*100/spolu}
        elements.append(Paragraph(txt,style=style['Normal']))
        
        #vykonnosti
        spolu=sum(vykonnosti.values())
        txt='<b>Výkonnostné kategórie</b>'
        elements.append(Paragraph(txt,style=style['Heading1']))
        txt=''
        for i in vykonnosti:
            txt+=i+': <b>%(pocet)d</b> (%(percenta)1.1f%%) ' % {'pocet':vykonnosti[i], 'percenta': float(vykonnosti[i])*100/spolu}
        elements.append(Paragraph(txt,style=style['Normal']))

        #kluby
        spolu=sum(kluby.values())
        txt='<b>Kluby</b>'
        elements.append(Paragraph(txt,style=style['Heading1']))
        txt=''
        for i in sorted(kluby, key=kluby.get, reverse=True):
            txt+=i+': <b>%(pocet)d</b> (%(percenta)0.1f%%) ' % {'pocet':kluby[i], 'percenta': 100*float(kluby[i])/spolu}
        elements.append(Paragraph(txt,style=style['Normal']))
        
        #plemena
        spolu=sum(plemena.values())
        txt='<b>Plemená</b>'
        elements.append(Paragraph(txt,style=style['Heading1']))
        txt=''
        for i in sorted(plemena, key=plemena.get, reverse=True):
            txt+=i+': <b>%(pocet)d</b> (%(percenta)0.1f%%) ' % {'pocet':plemena[i], 'percenta': 100*float(plemena[i])/spolu}
        elements.append(Paragraph(txt,style=style['Normal']))
        txt=''
        for i in pp:
            txt+=('s PP' if i==1 else 'bez PP')+': <b>%(pocet)d</b> (%(percenta)1.1f%%) ' % {'pocet':pp[i], 'percenta':float(pp[i])*100/spolu}
        elements.append(Paragraph(txt,style=style['Normal']))
        
        #krajiny
        spolu=sum(krajiny.values())
        txt='<b>Krajiny</b>'
        elements.append(Paragraph(txt,style=style['Heading1']))
        txt=''
        for i in sorted(krajiny, key=krajiny.get, reverse=True):
            I = Image("../icons/flags_iso/48/%(flag)s.png" % {"flag":i})
            I.drawHeight = 0.5*cm*I.drawHeight / I.drawWidth
            I.drawWidth = 0.5*cm
            txt='<b>'+i+'</b>: %(pocet)d</b> (%(percenta)d%%) ' % {'pocet':krajiny[i], 'percenta': round(100*krajiny[i]/spolu)}
            elements.append(ParagraphAndImage(Paragraph(txt,style=style['Normal']),I,3,3,'left'))

        doc.build(elements)
        os.popen(self.execstr+' statistika.pdf')

    def vysledky(self,behid,preteky):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        beh=preteky.behy.get(1)[behid]
        fname='vysledok'+str(behid)+'_'+beh[2]+'_'+beh[1]+'.pdf'
        doc = ARTemplate(fname, pagesize=landscape(A4),
                                rightMargin=1*cm,leftMargin=1*cm,
                                topMargin=1*cm,bottomMargin=1.5*cm)
        doc.udaje=preteky.udaje.get(1)
        doc.nazov=beh[0]
        startovka={}
        vyscache={}
        filter=beh[4]
        vysledky=preteky.vysledky.getBeh(behid)
        for id,zaznam in preteky.startovka.get():
            #print zaznam
            kat=zaznam[0]
            if (len(filter)==1):
                if (filter==kat[0:1]):
                    startovka[id]=zaznam
                    try:
                        vyscache[id]=vysledky[id]
                    except KeyError:
                        vyscache[id]=(behid, id, 0,0,0,0,200,u'-',0,0)
            elif (len(filter)==3):
                if (filter==kat):
                    startovka[id]=zaznam
                    try:
                        vyscache[id]=vysledky[id]
                    except KeyError:
                        vyscache[id]=(behid, id, 0,0,0,0,200,u'-',0,0)
        print vyscache
        #print beh
        #print startovka
        style = getSampleStyleSheet()
        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=12
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=-0.2*cm
        style['Heading1'].firstLineIndent=0
        
        style['Normal'].fontName='Ubuntu'
        style['Normal'].fontSize=7
        style['Normal'].leading=9
        style['Normal'].spaceAfter=4
        style['Normal'].spaceBefore=8
        style['Normal'].leftIndent=-0.2*cm
        style['Normal'].firstLineIndent=0
        tableStyle=[('GRID',(0,0),(-1,-1),0.3,colors.black),
                    ('BACKGROUND',(0,0),(-1,0),colors.lightgrey),
                    ('FONT', (0,0), (-1,0), 'Ubuntu-Bold'),
                    ('FONT', (0,1), (-1,-1), 'Ubuntu'),
                    ('FONTSIZE',(0,0),(-1,0), 6),
                    ('FONTSIZE',(0,0),(-1,-1), 7),
                    ('FONTSIZE',(3,1),(3,-1), 5),
                    ('ALIGN',(3,1),(3,-1),'CENTER'),
                    #('FONTSIZE',(5,1),(5,-1), 5), #klub
                    #('FONTSIZE',(7,1),(7,-1), 5), #plemeno
                    #('FONTSIZE',(1,1),(2,-1), 5), #c, kat
                    ('LEFTPADDING',(0,0),(-1,-1), 2),
                    ('TOPPADDING',(0,0),(-1,-1), 1),
                    ('RIGHTPADDING',(0,0),(-1,-1), 2),
                    ('BOTTOMPADDING',(0,0),(-1,-1), 1),
                    ('BOTTOMPADDING',(3,0),(3,-1), 2), #vlajky
                    ('ROWBACKGROUNDS',(0,1),(-1,-1), (None,0xE0E0E0)),
                    #('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    #('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    #('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    #('BOX',(0,0),(-1,-1),2,colors.black),
                    #('GRID',(0,0),(-1,-1),0.5,colors.black),
                    ('VALIGN',(0,1),(-1,-1),'MIDDLE'),
                    #('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    #('BACKGROUND',(3,1),(3,1),colors.khaki),
                    ('ALIGN',(0,1),(0,-1),'RIGHT'),
                    ('ALIGN',(9,1),(0,-1),'RIGHT'),
                    #('BACKGROUND',(3,2),(3,2),colors.beige),
                    #('ALIGN',(3,2),(3,2),'LEFT'),
                    ]
        # container for the 'Flowable' objects
        elements = [Spacer(1, cm*2.5)]
        kat=""
        tableHeader=(u'Por.',u'Č.',u'Kat.',u'VZ',u'',u'Meno psovoda',u'Klub',u'Meno psa',u'Plemeno',u'CH',u'ODM',u'čas',u'TB č.',u'TB',u'Post. r.',u'H',u'B')
        colWidths=[0.7*cm, 0.7*cm, 0.7*cm, 1*cm,0.5*cm,3.5*cm, 4.2*cm, 5*cm, 4.5*cm, 0.7*cm,0.7*cm,1*cm,1*cm,1*cm,1*cm,0.7*cm,0.7*cm]
        vlistina=[tableHeader]
        
        poradie=1
        stats={'start':0,'0':0, 'V':0, 'VD':0, 'D':0, 'BO': 0, 'DIS': 0, 'maxr':0, 'avgr':0}
        for key in sorted(vyscache, key=vyscache.__getitem__, cmp=fciSort):
            r=vyscache[key]
            s=startovka[r[1]]
            #print 's'
            #print s
            #print 'r'
            #print r
            I = Image("../icons/flags_iso/48/%(flag)s.png" % {"flag":s[11]})
            I.drawHeight = 0.3*cm*I.drawHeight / I.drawWidth
            I.drawWidth = 0.3*cm
            vlistina.append((poradie if r[6]<100 else '-',key, s[0], s[7],I, s[1]+' '+s[2], s[3], s[4], s[5], r[3], r[4], \
                             '%(cas)1.2f' % {'cas':r[2]} if r[2]>0 else '-', r[5], r[6], \
                             '%(post)1.2f' % {'post': beh[5]/r[2]} if r[2]>0  else '-',preteky.vysledky.hodnotenie(r[6]),r[9]))
            poradie+=1
            h=preteky.vysledky.hodnotenie(r[6])
            if (h<>'-'):
                stats['start']+=1
                stats[h]+=1
                stats['avgr']+=beh[5]/r[2] if r[2]>0 else 0
                if r[6]==0:
                    stats['0']+=1
                if r[2]>0 and r[6]<100:
                    stats['maxr']=beh[5]/r[2] if beh[5]/r[2]>0 else stats['maxr']
        stats['avgr']/=stats['start']
        print stats
        t=Table(vlistina,style=tableStyle,repeatRows=1)
        t._argW=colWidths
        
        elements.append(Paragraph( \
        u'Dátum: %(datum)s<br/>Rozhodca: %(rozhodca)s<br/>Dĺžka parkúru: %(dlzka)1.1f m<br/>Počet prekážok: %(pocet)d<br/>Štandardný čas: %(stdcas)1.2f s (%(stdr)1.2f m/s)<br/>Maximálny čas: %(maxcas)1.2f s (%(maxr)1.2f m/s)<br/>Počet tímov: %(pocett)d' % \
        {'datum': beh[2], 'rozhodca': beh[3], 'dlzka': beh[5], 'pocet': beh[8], 'stdcas': beh[6], 'stdr': beh[5]/beh[6], 'maxcas': beh[7], 'maxr': beh[7]/beh[6], 'pocett': len(vyscache) } \
        ,style=style['Normal']
        ))
        
        elements.append(t)
        
        elements.append(Paragraph( \
        u'Štartovali: %(start)d (%(startp)d%%), Čisté behy: %(ciste)d (%(cistep)d%%) V: %(v)d (%(vp)d%%), VD: %(vd)d (%(vdp)d%%), D: %(d)d (%(dp)d%%), BO: %(bo)d (%(bop)d%%), DIS: %(dis)d (%(disp)d%%), Priemerná postupová rýchlosť: %(avgr)1.2f m/s, Maximálna postupová rýchlost: %(maxr)1.2f m/s' % \
        {'start': stats['start'], 'startp': stats['start']*100/len(vyscache), 'ciste': stats['0'], 'cistep': stats['0']*100/len(vyscache), \
         'v': stats['V'], 'vp': stats['V']*100/len(vyscache),'vd': stats['VD'], 'vdp': stats['VD']*100/len(vyscache), \
         'd': stats['D'], 'dp': stats['D']*100/len(vyscache),'bo': stats['BO'], 'bop': stats['BO']*100/len(vyscache), \
         'dis': stats['DIS'], 'disp': stats['DIS']*100/len(vyscache), 'avgr': stats['avgr'], 'maxr': stats['maxr']}, \
         style=style['Normal']
        ))
        doc.build(elements)
        os.popen(self.execstr+' '+fname)
    
    def vysledkySucet(self,sucetid,preteky):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        sucet=preteky.sucty.get(1)[sucetid]
        #print sucet
        typ=sucet[1] #typ suctu, 1=FCI, 2=body
        filter=sucet[3]
        behy=string.split(sucet[2], ';')
        fname='vysledok'+str(sucetid)+'_'+sucet[0]+'.pdf'
        fname=fname.replace(' ','_')
        doc = ARTemplate(fname, pagesize=landscape(A4),
                                rightMargin=1*cm,leftMargin=1*cm,
                                topMargin=1*cm,bottomMargin=1.5*cm)
        doc.udaje=preteky.udaje.get(1)
        doc.nazov=sucet[0]

        startovka={}
        vyscache={}
        #vystotal={}
        #behdata={}
        for id,zaznam in preteky.startovka.get():
            if filter=="PP":
                if zaznam[6]==1:
                    startovka[id]=zaznam
            else:
                startovka[id]=zaznam
        vysledky=preteky.getSucet(sucetid)

        #print beh
        #print startovka
        style = getSampleStyleSheet()
        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=12
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=-0.2*cm
        style['Heading1'].firstLineIndent=0
        
        style['Normal'].fontName='Ubuntu'
        style['Normal'].fontSize=7
        style['Normal'].leading=9
        style['Normal'].spaceAfter=4
        style['Normal'].spaceBefore=8
        style['Normal'].leftIndent=-0.2*cm
        style['Normal'].firstLineIndent=0
        tableStyle=[('GRID',(0,0),(-1,-1),0.3,colors.black),
                    ('BACKGROUND',(0,0),(-1,0),colors.lightgrey),
                    ('FONT', (0,0), (-1,0), 'Ubuntu-Bold'),
                    ('FONT', (0,1), (-1,-1), 'Ubuntu'),
                    ('FONTSIZE',(0,0),(-1,0), 6),
                    ('FONTSIZE',(0,0),(-1,-1), 7),
                    #('FONTSIZE',(5,1),(5,-1), 5), #klub
                    #('FONTSIZE',(7,1),(7,-1), 5), #plemeno
                    #('FONTSIZE',(1,1),(2,-1), 5), #c, kat
                    ('LEFTPADDING',(0,0),(-1,-1), 2),
                    ('TOPPADDING',(0,0),(-1,-1), 1),
                    ('RIGHTPADDING',(0,0),(-1,-1), 2),
                    ('BOTTOMPADDING',(0,0),(-1,-1), 1),
                    ('BOTTOMPADDING',(3,0),(3,-1), 2), #vlajky
                    ('ROWBACKGROUNDS',(0,1),(-1,-1), (None,0xE0E0E0)),
                    #('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    #('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    #('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    #('BOX',(0,0),(-1,-1),2,colors.black),
                    #('GRID',(0,0),(-1,-1),0.5,colors.black),
                    ('VALIGN',(0,1),(-1,-1),'MIDDLE'),
                    #('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    #('BACKGROUND',(3,1),(3,1),colors.khaki),
                    ('ALIGN',(0,1),(0,-1),'RIGHT'),
                    ('ALIGN',(8,1),(0,-1),'RIGHT'),
                    #('BACKGROUND',(3,2),(3,2),colors.beige),
                    #('ALIGN',(3,2),(3,2),'LEFT'),
                    ]
        # container for the 'Flowable' objects
        elements = [Spacer(1, cm*2.5)]
        kat=""
        tableHeader=(u'Por.',u'Č.',u'Kat.',u'',u'Meno psovoda',u'Klub',u'Meno psa',u'Plemeno')
        colWidths=[0.7*cm, 0.7*cm, 0.7*cm, 0.5*cm,4.3*cm, 4.5*cm, 5*cm, 4.5*cm]
        if typ==1: #fci sucet
            bid=1
            for b in behy:
                tableHeader+=(u'čas'+str(bid), u'TB'+str(bid),)
                colWidths+=[0.7*cm,1*cm]
                #,1*cm,1*cm,1*cm,1*cm,0.7*cm,0.7*cm]
                bid+=1
            tableHeader+=(u'Čas',u'TB',)
            colWidths+=[1*cm,1*cm]
        else: #bodovy
            bid=1
            for b in behy:
                tableHeader+=(u'b'+str(bid),)
                colWidths+=[0.7*cm]
                bid+=1
            tableHeader+=(u'Spolu',)
            colWidths+=[1*cm]
        
        #0.7*cm,0.7*cm,1*cm,1*cm,1*cm,1*cm,0.7*cm,0.7*cm]
        vlistina=[tableHeader]
        
        #uprav sirku na 27.7
        zvysok=(27.7*cm-sum(colWidths))/4
        for i in range(4, 8):
            colWidths[i]+=zvysok 
        
        poradie=1
        #stats={'start':0,'0':0, 'V':0, 'VD':0, 'D':0, 'BO': 0, 'DIS': 0, 'maxr':0, 'avgr':0}
        vyscache=vysledky[1]
        for key in vysledky[0]:
            r=vysledky[0][key]
            print 'r'
            print r
            s=startovka[r[0]]
            print 's'
            print s
            print 'vyscache'
            print vyscache
            I = Image("../icons/flags_iso/48/%(flag)s.png" % {"flag":s[11]})
            I.drawHeight = 0.3*cm*I.drawHeight / I.drawWidth
            I.drawWidth = 0.3*cm
            
            if typ==1: #fci
                poradie2=poradie if r[1][0]>1 else '-'
            else:
                poradie2=poradie if r[1][2]>0 else '-'
            riadok=(poradie2,r[0], s[0], I, s[1]+' '+s[2], s[3], s[4], s[5])
            if typ==1: #fci
                for b in behy:
                    riadok+=('%(cas)1.2f' % {'cas':vyscache[r[0]][int(b)][2]} if vyscache[r[0]][int(b)][2]>0 else '-',vyscache[r[0]][int(b)][6],)
                riadok+=('%(cas)1.2f' % {'cas':r[1][2]} if r[1][2]>0 else '-',r[1][6],)
            else: #body
                for b in behy:
                    print 'riadok s vysledkom'
                    print vyscache[r[0]][int(b)]
                    print 'b'+b
                    riadok+=(vyscache[r[0]][int(b)][9],)
                riadok+=(r[1][0],)
            vlistina.append(riadok)
            poradie+=1
        t=Table(vlistina,style=tableStyle,repeatRows=1)
        t._argW=colWidths
        
        bid=1
        for b in behy:
            behdata=preteky.behy.get(1)[int(b)]
            print behdata
            elements.append(Paragraph( \
            u'Beh č. %(bid)d: %(beh)s (%(datum)s)' % \
            {'bid': int(bid), 'beh': behdata[0], 'datum': behdata[2]} \
            ,style=style['Normal']
            ))
            bid+=1
        
        elements.append(t)
        
        doc.build(elements)
        os.popen(self.execstr+' '+fname)

    def vitazi(self,preteky):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        sucty=preteky.sucty.get()
        behy=preteky.behy.get()
        
        fname='vitazi.pdf'
        doc = ARTemplate(fname, pagesize=A4,
                                rightMargin=1*cm,leftMargin=1*cm,
                                topMargin=1*cm,bottomMargin=1.5*cm)
        doc.udaje=preteky.udaje.get(1)
        doc.nazov=u'Vyhlasovanie víťazov'
        startovka=preteky.startovka.get(1)
        
        
        #print beh
        #print startovka
        style = getSampleStyleSheet()
        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=12
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=-0.2*cm
        style['Heading1'].firstLineIndent=0
        
        style['Normal'].fontName='Ubuntu'
        style['Normal'].fontSize=7
        style['Normal'].leading=9
        style['Normal'].spaceAfter=4
        style['Normal'].spaceBefore=8
        style['Normal'].leftIndent=-0.2*cm
        style['Normal'].firstLineIndent=0
        tableStyle=[('GRID',(0,0),(-1,-1),0.3,colors.black),
                    ('BACKGROUND',(0,0),(-1,0),colors.lightgrey),
                    ('FONT', (0,0), (-1,0), 'Ubuntu-Bold'),
                    ('FONT', (0,1), (-1,-1), 'Ubuntu'),
                    ('FONTSIZE',(0,0),(-1,0), 6),
                    ('FONTSIZE',(0,0),(-1,-1), 7),
                    ('FONTSIZE',(3,1),(3,-1), 5),
                    ('ALIGN',(3,1),(3,-1),'CENTER'),
                    #('FONTSIZE',(5,1),(5,-1), 5), #klub
                    #('FONTSIZE',(7,1),(7,-1), 5), #plemeno
                    #('FONTSIZE',(1,1),(2,-1), 5), #c, kat
                    ('LEFTPADDING',(0,0),(-1,-1), 2),
                    ('TOPPADDING',(0,0),(-1,-1), 1),
                    ('RIGHTPADDING',(0,0),(-1,-1), 2),
                    ('BOTTOMPADDING',(0,0),(-1,-1), 1),
                    ('BOTTOMPADDING',(3,0),(3,-1), 2), #vlajky
                    ('ROWBACKGROUNDS',(0,1),(-1,-1), (None,0xE0E0E0)),
                    #('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    #('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    #('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    #('BOX',(0,0),(-1,-1),2,colors.black),
                    #('GRID',(0,0),(-1,-1),0.5,colors.black),
                    ('VALIGN',(0,1),(-1,-1),'MIDDLE'),
                    #('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    #('BACKGROUND',(3,1),(3,1),colors.khaki),
                    ('ALIGN',(0,1),(0,-1),'RIGHT'),
                    ('ALIGN',(9,1),(0,-1),'RIGHT'),
                    #('BACKGROUND',(3,2),(3,2),colors.beige),
                    #('ALIGN',(3,2),(3,2),'LEFT'),
                    ]
        # container for the 'Flowable' objects
        elements = [Spacer(1, cm*2.5)]

        ostr=''
        for k,v in sucty:
            ostr+='<b>'+v[0]+'</b><br/>'
            vysledky=preteky.getSucet(k)[0]
            #print vysledky
            for i in range(0,3 if len(vysledky)>3 else len(vysledky)):
                #print vysledky[i+1][0]
                s2=startovka[vysledky[i+1][0]]
                #print s2
                ostr+='<b>'+str(i+1)+'.</b> '+s2[1]+' '+s2[2]+' ('+s2[3]+')  /  '
            ostr+='<br/>'
        for k,v in behy:
            #print k,v
            #behdata=preteky.behy.get(1)[k]
            ostr+='<b>'+v[0]+'</b> ('+v[2]+')<br/>'
            vysledky=preteky.vysledky.getBeh(k)
            
            poradie=1
            for key in sorted(vysledky, key=vysledky.__getitem__, cmp=fciSort):
                #print key,vysledky[key]
                if (poradie<=3):
                    s2=startovka[key]
                    ostr+='<b>'+str(poradie)+'.</b> '+s2[1]+' '+s2[2]+' ('+s2[3]+')  /  '
                poradie+=1
                #print s2
            ostr+='<br/>'
        elements.append(Paragraph(ostr,style=style['Normal']))
        doc.build(elements)
        os.popen(self.execstr+' '+fname)
    
    
    def vz(self,preteky):
        addMapping('Ubuntu', 0, 0, 'Ubuntu')    #normal
        addMapping('Ubuntu', 0, 1, 'Ubuntu-Italic')    #italic
        addMapping('Ubuntu', 1, 0, 'Ubuntu-Bold')    #bold
        addMapping('Ubuntu', 1, 1, 'Ubuntu-BoldItalic')    #italic and bold

        sucty=preteky.sucty.get()
        behy=preteky.behy.get()
        
        rH=1.2375*cm-(0.2*cm/22)
        
        fname='VZ.pdf'
        doc = ARTemplateVZ(fname, pagesize=A4,
                                rightMargin=0.5*cm,leftMargin=0.5*cm,
                                topMargin=rH-0.05*cm,bottomMargin=0)
        doc.udaje=preteky.udaje.get(1)
        startovka=preteky.startovka.get(1)
        
        #print beh
        #print startovka
        style = getSampleStyleSheet()
        style['Heading1'].fontName='Ubuntu'
        style['Heading1'].fontSize=12
        style['Heading1'].leading=14
        style['Heading1'].spaceAfter=4
        style['Heading1'].spaceBefore=8
        style['Heading1'].leftIndent=-0.2*cm
        style['Heading1'].firstLineIndent=0
        
        style['Normal'].fontName='Ubuntu'
        style['Normal'].fontSize=7
        style['Normal'].leading=9
        #style['Normal'].spaceAfter=4
        #style['Normal'].spaceBefore=8
        style['Normal'].leftIndent=-0.2*cm
        style['Normal'].firstLineIndent=0
        tableStyle=[('GRID',(0,0),(-1,-1),0.3,colors.lightgrey),
                    ('FONT', (0,0), (-1,-1), 'Ubuntu'),
                    ('FONTSIZE',(0,0),(-1,-1), 10),
                    #zarovnanie na stred bunky
                    ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                    ('ALIGN',(0,0),(-1,-1),'CENTER'),
                    #datum
                    ('FONTSIZE',(0,0),(0,-1), 7),
                    #skuska
                    ('FONT', (2,0), (2,-1), 'Ubuntu-Bold'), 
                    ('FONTSIZE',(2,0),(2,-1), 12),
                    #tb, hodnotenie, poradie
                    ('FONT', (6,0), (8,-1), 'Ubuntu-Bold'), 
                    ('FONTSIZE',(6,0),(8,-1), 12),
                    #rozhodca
                    ('FONTSIZE',(9,0),(9,-1), 8),
                    
                    #preteky
                    ('LEFTPADDING',(1,0),(1,-1), 0.3*cm),
                    
                    #('FONTSIZE',(5,1),(5,-1), 5), #klub
                    #('FONTSIZE',(7,1),(7,-1), 5), #plemeno
                    #('FONTSIZE',(1,1),(2,-1), 5), #c, kat
                    #('LEFTPADDING',(0,0),(-1,-1), 2),
                    #('TOPPADDING',(0,0),(-1,-1), 1),
                    #('RIGHTPADDING',(0,0),(-1,-1), 2),
                    #('BOTTOMPADDING',(0,0),(-1,-1), 1),
                    #('BOTTOMPADDING',(3,0),(3,-1), 2), #vlajky
                    #('ROWBACKGROUNDS',(0,1),(-1,-1), (None,0xE0E0E0)),
                    #('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    #('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    #('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    #('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    #('BOX',(0,0),(-1,-1),2,colors.black),
                    #('GRID',(0,0),(-1,-1),0.5,colors.black),
                    #('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    #('BACKGROUND',(3,1),(3,1),colors.khaki),
                    #('ALIGN',(9,1),(0,-1),'RIGHT'),
                    #('BACKGROUND',(3,2),(3,2),colors.beige),
                    #('ALIGN',(3,2),(3,2),'LEFT'),
                    ]
        # container for the 'Flowable' objects
        elements = []

#===============================================================================
# 05mm prazdne
# 
# 12mm datum
# 40mm miesto/organizator
# 12mm beh
# 15mm TB na trati
# 16mm TB cas
# 
# 10mm prazdne
# 
# 15mm TB spolu
# 15mm hodnotenie
# 15mm poradie
# 25mm rozhodca
# 25mm podpis
# 
# 
# vyska: 15mm
#===============================================================================


        #tableHeader=(u'Por.',u'Č.',u'Kat.',u'',u'Meno psovoda',u'Klub',u'Meno psa',u'Plemeno')
        colWidths=[1.2*cm, 4*cm, 1.2*cm, 1.5*cm,1.6*cm, 1*cm, 1.5*cm,1.5*cm,1.5*cm,2.5*cm, 2.5*cm]
        rowHeights=[]
        vzs=[]
        stlpcov=0
        for k,v in behy:
            #print k,v
            behdata=preteky.behy.get(1)[k]
            if len(behdata[4])==3:
                vysledky=preteky.vysledky.getBeh(k)
                poradie=1
                print behdata[4]
                print vysledky
                udaje=preteky.udaje.get(1)
                #bd[4] LA3 [2] datum [3] rozhodca
                
                pocet=0
                for key in sorted(vysledky, key=vysledky.__getitem__, cmp=fciSort):
                    v2=vysledky[key]
                    if v2[6]<200:
                        pocet+=1
                for key in sorted(vysledky, key=vysledky.__getitem__, cmp=fciSort):
                    #print key,vysledky[key]
                    v2=vysledky[key]
                    if v2[6]<200:
                        vzs.append((behdata[2], \
                                #'<b>'+udaje['nazov']+'</b>\n'+udaje['organizator'] \
                                Paragraph('<center><font size="10">'+udaje['nazov']+'</font><br/>' \
                                          +'<font size="6">'+udaje['organizator']+'</font><br/>' \
                                          +'<font size="4">'+startovka[v2[1]][2]+' '+startovka[v2[1]][1]+' + '+startovka[v2[1]][4]+'</font></center>' \
                                          ,style['Normal'])
                                , behdata[4],(v2[3]+v2[4])*5 if v2[6]<100 else '-',v2[5] if v2[6]<100 else '-','',v2[6] if v2[6]<100 else '-', \
                               preteky.vysledky.hodnotenie(v2[6]), (str(poradie)+'.' if v2[6]<100 else '-')+'/'+str(pocet), behdata[3],''))
                    #Paragraph('<font size="20">test</font>ss',style['Normal'])
                        rowHeights+=[rH]
                    poradie+=1
        
        t=Table(vzs,colWidths,rowHeights)
        t.setStyle(tableStyle)
        #t._argW=colWidths
        #t._argH=rowHeights
        #t._argH=stlpcov*[1.5*cm]
        elements.append(t)
        doc.build(elements)
        os.popen(self.execstr+' '+fname)
        
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if locale<>'sk_SK':
        if qtTranslator.load("agilityregister_"+locale+".qm"):
            app.installTranslator(qtTranslator)

    f = AgilityRegister()
    QtCore.QObject.connect(app,QtCore.SIGNAL("lastWindowClosed()"),app,QtCore.SLOT("quit()"))
    QtCore.QObject.connect(f.ui.actionUkon_i,QtCore.SIGNAL("triggered()"),f.confirmQuit)
    f.connect(f.ui.actionZvoli_preteky,QtCore.SIGNAL("triggered()"),f.vybratPretekyMenu)
    f.connect(f.ui.actionZ_kladn_info,QtCore.SIGNAL("triggered()"),f.udajeEditorMenu)
    f.connect(f.ui.actionLicencia,QtCore.SIGNAL("triggered()"),f.aboutWindow)
    f.connect(f.ui.actionBehy,QtCore.SIGNAL("triggered()"),f.behyEditorMenu)
    f.connect(f.ui.action_tartovka,QtCore.SIGNAL("triggered()"),f.startovkaEditorMenu)
    f.connect(f.ui.nastavBehButton,QtCore.SIGNAL("clicked()"),f.nastavBeh)
    f.connect(f.ui.pushButton_2,QtCore.SIGNAL("clicked()"),f.nextTim)
    f.connect(f.ui.pushButton,QtCore.SIGNAL("clicked()"),f.prevTim)
    f.connect(f.ui.stopButton,QtCore.SIGNAL("clicked()"),f.startStop)
    f.connect(f.ui.copyTimeButton,QtCore.SIGNAL("clicked()"),f.copyTime)
    f.connect(f.ui.chybaButtonAdd,QtCore.SIGNAL("clicked()"),f.chybaPlus)
    f.connect(f.ui.chybaButtonRemove,QtCore.SIGNAL("clicked()"),f.chybaMinus)
    f.connect(f.ui.odmietnutieButtonAdd,QtCore.SIGNAL("clicked()"),f.odmPlus)
    f.connect(f.ui.odmietnutieButtonRemove,QtCore.SIGNAL("clicked()"),f.odmMinus)
    f.connect(f.ui.saveButton,QtCore.SIGNAL("clicked()"),f.ulozVysledok)
    f.connect(f.ui.behyTable,QtCore.SIGNAL("itemDoubleClicked(QTableWidgetItem*)"),f.nastavBeh)
    f.connect(f.ui.vysledkyButton,QtCore.SIGNAL("clicked()"),f.exportVysledkyBehu)
    f.connect(f.ui.action_tartovn_listina,QtCore.SIGNAL("triggered()"),f.pdfStartovka)
    f.connect(f.ui.actionPrezen_n_listina,QtCore.SIGNAL("triggered()"),f.pdfPrezencka)
    f.connect(f.ui.action_tatistika,QtCore.SIGNAL("triggered()"),f.pdfStatistika)
    f.connect(f.ui.actionFormul_re_pre_zapisovate_ov,QtCore.SIGNAL("triggered()"),f.pdfZapis)
    f.connect(f.ui.resetButton,QtCore.SIGNAL("clicked()"),f.swapRezim)
    f.connect(f.ui.actionVyhlasovanie_v_azov,QtCore.SIGNAL("triggered()"),f.pdfVitazi)
    f.connect(f.ui.actionSamolepky_do_VZ,QtCore.SIGNAL("triggered()"),f.pdfVZ)
    #QtCore.QObject.connect(self.ui.actionTest, QtCore.SIGNAL('triggered()'), self.actionTest)
    f.ui.resetButton.setText('A->A')

    f.show()
    f.aboutWindow()
    f.vybratPretekyMenu()
    sys.exit(app.exec_())
